package com.zhibi.util.codec.rsa;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

import com.zhibi.util.codec.base64.BASE64Util;
import com.zhibi.util.codec.common.HexStrUtil;


/**
 * RSA 加解密工具   对密钥进行加密
 * @author Administrator
 *
 */
public class RSAUtil {

	private static KeyFactory keyFactory;
	private static KeyPairGenerator keyPairGen;//用于生成公钥和私钥对，基于RSA算法生成对象  
	private static KeyPair keyPair;
	private static String KEY_ALGORTHM = "RSA";

	static{
		try {
			keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
			keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORTHM);
			//初始化密钥对生成器，密钥大小为1024位  
			keyPairGen.initialize(1024);
			keyPair= keyPairGen.generateKeyPair();//生成一个密钥对，保存在keyPair中  
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加密
	 * @param publicKey
	 * @param srcBytes
	 * @return
	 */
	public static String encrypt(String publicKey,String content,String charset){  
		if(charset==null || charset.isEmpty()){
			charset = "utf-8";
		}
		if(publicKey!=null){
			try {
				KeySpec keySpec = new X509EncodedKeySpec(BASE64Util.decrypt(publicKey));
				Key key = keyFactory.generatePublic(keySpec);
				//Cipher负责完成加密或解密工作，基于RSA  
				Cipher cipher = Cipher.getInstance(KEY_ALGORTHM);  
				//根据公钥，对Cipher对象进行初始化  
				cipher.init(Cipher.ENCRYPT_MODE, key);  
				return HexStrUtil.parseByte2HexStr(cipher.doFinal(content.getBytes(charset)));  
			} catch (Exception e) {
				e.printStackTrace();
			}
		}  
		return null;  
	}  

	/**
	 * 解密
	 * @param privateKey
	 * @param srcBytes
	 * @return
	 */
	public static String decrypt(String privateKey,String content,String charset){  
		if(charset==null || charset.isEmpty()){
			charset = "utf-8";
		}
		if(privateKey!=null){  
			try {
				KeySpec keySpec = new PKCS8EncodedKeySpec(BASE64Util.decrypt(privateKey));
				Key key = keyFactory.generatePrivate(keySpec);
				//Cipher负责完成加密或解密工作，基于RSA  
				Cipher cipher = Cipher.getInstance(KEY_ALGORTHM);  
				//根据公钥，对Cipher对象进行初始化  
				cipher.init(Cipher.DECRYPT_MODE, key);  
				return new String(cipher.doFinal(HexStrUtil.parseHexStr2Byte(content)),charset);  
			} catch (Exception e) {
				e.printStackTrace();
			}
		}  
		return null;  
	}  

	/**
	 * 得到公钥
	 * @return
	 */
	public static String getPublicKey(){
		return BASE64Util.encrypt(keyPair.getPublic().getEncoded()).toString();
	}

	/**
	 * 得到私钥
	 * @return
	 */
	public static String getPrivateKey(){
		return BASE64Util.encrypt(keyPair.getPrivate().getEncoded()).toString();
	}
}
